/**
 * Copyright (c) Software Institute of PKU
 * All rights reserved. 
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 */
package edu.pku.sei.modeler.editparts;

import java.beans.PropertyChangeEvent;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.DirectEditPolicy;
import org.eclipse.gef.requests.DirectEditRequest;

import edu.pku.sei.modeler.commands.ChangeNameCommand;
import edu.pku.sei.modeler.edit.parts.AbstractNodeEditPart;
import edu.pku.sei.modeler.model.core.CorePackage;
import edu.pku.sei.modeler.model.core.MetaNamedElement;
import edu.pku.sei.modeler.model.structure.MetaNode;
import edu.pku.sei.modeler.model.structure.MetaShapeElement;

/**
 * @author zl
 * 
 */
public abstract class MetaNamedElementEditPart extends AbstractNodeEditPart {

	public MetaNamedElementEditPart(MetaShapeElement model) {
		super(model);
	}

	protected DirectEditPolicy createDirectEditPolicy() {
		return new DirectEditPolicy() {
			protected Command getDirectEditCommand(DirectEditRequest request) {
				return new ChangeNameCommand(getNamedElement(),
						(String) request.getCellEditor().getValue());
			}

			protected void showCurrentEditValue(DirectEditRequest request) {
				IFigure fig = getDirectEditFigure();
				if (fig instanceof Label) {
					((Label) fig).setText(getNamedElement().getName());
					fig.getUpdateManager().performUpdate();
				}
			}
		};
	}

	protected void createEditPolicies() {
		super.createEditPolicies();
	}

	protected void handlePropertyChanged(PropertyChangeEvent event) {
		String propertyName = event.getPropertyName();
		if(propertyName.equals(CorePackage.NAMEDELEMENT_NAME)) {
			refreshVisuals();
		}
		super.handlePropertyChanged(event);
	}
	
	protected MetaNamedElement getNamedElement() {
		return (MetaNamedElement)((MetaNode)getModel()).getModelElement();
	}
}
